package api.actions;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import api.Interface;
import api.dialogs.InitRandomObsDialog;
import api.dialogs.RandomObsDialog;

public class RandomObs {
	public static int p = 1;
	
	public static void run() {		 
		final InitRandomObsDialog dialogInit = new InitRandomObsDialog();
		
		dialogInit.btnAceptar_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dialogInit.setVisible(false);
								
				final RandomObsDialog dialog = new RandomObsDialog();
				crearRObs();
				
				dialog.btnAceptar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						dialog.setVisible(false);
						
						Interface.MostrarCasillas();
					}
				});				
				
				dialog.lblNObs.setText("" + Interface.getTablero().getObs().size());
				dialog.setVisible(true);
			}
		});
		
		dialogInit.slider.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {;
				p = (Integer) dialogInit.slider.getValue();
				dialogInit.label.setText(new String("" + p));
			}
		});
		
		dialogInit.setVisible(true);
	}
	
	public static void crearRObs () {
		int numObs = (int) (Interface.getTablero().getM() * Interface.getTablero().getN() * (p / 100.0));		
		
		Random rndX = new Random();
		Random rndY = new Random();
		
		rndX.setSeed(new Date().getTime());
		rndY.setSeed(3816);
		
		Point p = new Point(0,0);
		Point ini = Interface.getTablero().getRobot().getPosInicial();
		Point fin = Interface.getTablero().getRobot().getPosFinal();
		
		HashSet<Point> s = new HashSet<Point>(); 
		
		while(numObs != 0) {
			p.setLocation(rndX.nextInt(Interface.getTablero().getM()), 
					rndY.nextInt(Interface.getTablero().getN()));
			
			if (!s.contains(p) && !p.equals(ini) && !p.equals(fin)) {
				s.add(new Point((int) p.getX(), (int) p.getY()));
				numObs--;
			} 
		}			
		
		Interface.getTablero().SetObs(s);
	}
}
